package com.bytz.modules.cms.order.schedule;

import cn.hutool.core.bean.BeanUtil;
import com.bytz.common.system.vo.LoginUser;
import com.bytz.common.util.SecurityUtils;
import com.bytz.modules.cms.order.constant.OrderPayConstants;
import com.bytz.modules.cms.order.entity.Order;
import com.bytz.modules.cms.order.entity.OrderPayDetail;
import com.bytz.modules.cms.order.service.*;
import com.bytz.modules.system.service.ISysUserService;
import com.bytz.modules.system.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
@Slf4j
public class CancelOrderJob implements Job {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderPayDetailService orderPayDetailService;
    @Autowired
    private IOrderPayService orderPayService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

        SysUserVo syscall = sysUserService.getUserByName("syscall");
        SecurityUtils.setLoginUser(BeanUtil.copyProperties(syscall, LoginUser.class));

        List<String> orderIds = orderService.getPaymentOvertimeOrder()
                .stream().map(Order::getId)
                .collect(Collectors.toList());
        for (String orderId : orderIds) {
            try {
                boolean hasPaying = false;
                for (OrderPayDetail orderPayDetail : orderPayDetailService.getByOrderId(orderId)) {
                    if (OrderPayConstants.PayStatus.PAYING.equals(orderPayDetail.getStatus())) {
                        if (orderPayDetail.getExpirationTime() == null || orderPayDetail.getExpirationTime().isAfter(LocalDateTime.now())) {
                            hasPaying = true;
                        } else {
                            orderPayService.rollbackPay(orderPayDetail);
                        }
                    }
                }

                if (!hasPaying) {
                    orderService.updateOrderExpired(orderId);
                    log.info("订单超时过期，order:" + orderId);
                } else {
                    log.info("订单已超时，但存在正在支付的记录，无法关闭，order:" + orderId);
                }
            } catch (Exception e) {
                log.error("将支付过期订单标记为作废失败，order:" + orderId, e);
            }
        }

        SecurityUtils.setLoginUser(null);
    }
}
